# -*- coding: utf-8 -*-
import codecs

from django.conf import settings
from django.shortcuts import get_object_or_404
from django.views.generic import ListView
from django.views.generic import DeleteView
from django.views.generic.edit import CreateView
from django.views.generic.edit import UpdateView
from django.http import HttpResponseRedirect
from django.utils.translation import ugettext as _

from mediabox.lira.utils import get_messages
from mediabox.lira.utils import set_messages
from mediabox.lira.utils import get_msgfile

from mediabox.lira.models import Region
from mediabox.lira.forms import RegionForm

class RegionNew(CreateView):
    form_class = RegionForm
    success_url = '/manage/regions'
    template_name = 'regions/manage/region_new.html'

    def form_valid(self, form):
        msg_filename = get_msgfile(self.request)
        messages = [{'type': 'success', 'message': _('Region saved'), }]

        if set_messages(filename=msg_filename, messages=messages):
            self.request.session['msg_file'] = msg_filename

        return super(RegionNew, self).form_valid(form)

    def form_invalid(self, form):
        msg_filename = get_msgfile(self.request)
        messages = [{'type': 'errormsg', 'message': _('Please fill in the form'), }]

        if set_messages(filename=msg_filename, messages=messages):
            self.request.session['msg_file'] = msg_filename

        return super(RegionNew, self).form_invalid(form)

    def get_context_data(self, **kwargs):
        context = super(RegionNew, self).get_context_data(**kwargs)

        if self.request.session.has_key('msg_file'):
            context['system_messages'] = get_messages(self.request.session['msg_file'], clear=True)
            del self.request.session['msg_file']

        return context

class RegionList(ListView):
    model = Region
    template_name = 'regions/manage/region_list.html'
    context_object_name = 'regions'
    queryset = Region.objects.all().order_by('-region_name')
    paginate_by = settings.PAGINATE_BY

    def get_context_data(self, **kwargs):
        context = super(RegionList, self).get_context_data(**kwargs)
        context['region_form'] = RegionForm()
        context['annotate_by'] = settings.ANNOTATE_BY

        if self.request.session.has_key('msg_file'):
            context['system_messages'] = get_messages(self.request.session['msg_file'], clear=True)
            del self.request.session['msg_file']

        return context

class RegionUpdate(UpdateView):
    form_class = RegionForm
    model = Region
    success_url = '/manage/regions'
    template_name = 'regions/manage/region_update.html'
    context_object_name = 'region'

    def form_valid(self, form):
        object = form.save(commit=False)
        object.save()
        msg_filename = get_msgfile(self.request)
        messages = [{'type': 'success', 'message': _('Region successfully updated'), }]

        if set_messages(filename=msg_filename, messages=messages):
            self.request.session['msg_file'] = msg_filename

        return HttpResponseRedirect(self.get_success_url())

    def form_invalid(self, form):
        msg_filename = get_msgfile(self.request)
        messages = [{'type': 'errormsg', 'message': _('Please fill in the form'), }]

        if set_messages(filename=msg_filename, messages=messages):
            self.request.session['msg_file'] = msg_filename

        return super(RegionUpdate, self).form_invalid(form)

    def get_object(self, queryset=None):
        return get_object_or_404(self.model, pk=self.kwargs.get('pk', None))

    def get_context_data(self, **kwargs):
        pk = self.kwargs.get('pk', None)
        context = super(RegionUpdate, self).get_context_data(**kwargs)
        context['object_id'] = pk

        if self.request.session.has_key('msg_file'):
            context['system_messages'] = get_messages(self.request.session['msg_file'], clear=True)
            del self.request.session['msg_file']

        return context

class RegionDelete(DeleteView):
    template_name = 'common/common_delete_template.html'
    success_url = '/manage/regions'
    context_object_name = 'item'

    def delete(self, request, *args, **kwargs):
        if 'delete' in self.request.POST['action'].lower():
            self.object = self.get_object()
            region = self.object.region_name
            self.object.delete()

            msg_filename = get_msgfile(self.request)
            messages = [{
                'type': 'success',
                'message': _('Region %s successfully deleted' % region),
            }]

            if set_messages(filename=msg_filename, messages=messages):
                self.request.session['msg_file'] = msg_filename

        return HttpResponseRedirect(self.get_success_url())

    def get_context_data(self, **kwargs):
        context = super(RegionDelete, self).get_context_data(**kwargs)
        context['form_action'] = self.request.META['PATH_INFO']

        return context

    def get_object(self, queryset=None):
        return get_object_or_404(Region, pk=self.kwargs.get('pk'))
